<template>
  <div class="carbon-credit-page">
    <!-- 顶部资产概览栏 -->
    <div class="top-header">
      <div class="header-left">
        <i class="el-icon-money"></i>
        <span class="title">我的碳配额资产</span>
      </div>
      <div class="header-middle">
        <span class="stat-item">持仓总量 <span class="stat-value">{{holdTotal}} (tCO₂e)&nbsp;|</span></span>  
        <span class="stat-item">可用数量 <span class="stat-value">{{available}} (tCO₂e)&nbsp;|</span></span> 
        <span class="stat-item">锁定数量 <span class="stat-value">{{locked}}(tCO₂e) &nbsp;|</span></span> 
        <span class="stat-item">冻结数量 <span class="stat-value">{{frozen}}(tCO₂e)</span></span>
      </div>
      <div class="header-right">
        <el-button type="primary" plain @click="fromVisible = true; dialogTitle = '上传碳信用项目'"
          >上传</el-button
        >
        <el-button type="success"  plain  @click="dialogVisible = true">我想买</el-button>
      </div>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <el-row :gutter="20" class="filter-row">
         <el-col :span="4">
          <div class="filter-item" style="display: flex; align-items: center;"> 
            <span class="filter-label">资产状态</span> 
            <el-select
              v-model="form.assetsStatus"
              placeholder="全部"
              clearable
              class="filter-select"
              style="flex: 1"
              @change="resetMainPagination"
            >
              <el-option v-for="item in assetsStatus" :label="item.itemCh" :value="item.itemValue":key="item.id" ></el-option>
            </el-select>
          </div>
        </el-col>

        <el-col :span="8">
     <div class="filter-item" style="display: flex; align-items: center; gap: 10px;"> 
        <span class="filter-label">有效日期</span> 
        <el-date-picker
          v-model="form.expiryDateStart"
          style="flex: 1;"
          type="date"
          placeholder="开始时间"
          clearable
          class="filter-date"
          value-format="yyyy-MM-dd"
          @change="resetMainPagination"
        ></el-date-picker>
        <span style="white-space: nowrap;">至</span>
        <el-date-picker
          v-model="form.expiryDateEnd"
          style="flex: 1;"
          type="date"
          placeholder="结束时间"
          clearable
          class="filter-date"
          value-format="yyyy-MM-dd"
          @change="resetMainPagination"
        ></el-date-picker>
      </div>
</el-col>
        <el-col :span="8">

          <div style="display: flex;" class="filter-item">
            <span style="margin-top: 8px;" class="filter-label2">关键词搜索</span>
            <div class="search-container">
              <el-input
                v-model="form.agencyName"
                placeholder="输入项目名称"
                clearable
                class="search-input"
                @keyup.enter.native="handleProjectSearch"
              ></el-input>
              <el-button type="success" plain @click="handleProjectSearch"
                >查询</el-button
              >
            </div>
          </div>
        </el-col>   
      </el-row>
    </div>

    <!-- 表格数据区域 -->
    <div class="table">
      <el-table
        :data="tableData"
        stripe
        @selection-change="handleSelectionChange"
        style=" width: 100%"
        v-loading="tableLoading"
      >
        <el-table-column   prop="id" align="center" label="序号" width="80"></el-table-column>
        <el-table-column
          prop="agencyName"
          label="一级市场持有机构"
          show-overflow-tooltip
          width="240"
        ></el-table-column>
        <el-table-column
          prop="availableAmount"
          label="持仓量(CO2e)"
          width="150"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="valuation"
          label="资产估值(¥)"
          width="170"
          align="center"
        ></el-table-column>
        
        <el-table-column
          prop="assetsStatus"
          label="资产状态"
          width="250"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="expiryDate"
          label="有效日期"
          width="130"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column label="操作" width="385" align="center">
          <template v-slot="scope">
            <div class="operation-btns">
              <span 
                class="btn-text view" 
                @click="handleView(scope.row.id)"
              >查看</span>
               <span class="btn-text offline" @click="handleOffline(scope.row)"
                >场外上架</span>
              <span 
                class="btn-text inner" 
                @click="handleInner(scope.row)"
              >场内交易</span>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination" v-if="mainTotal > 0">
        <el-pagination
          background
          @current-change="handleMainPageChange"
          @size-change="handleMainPageSizeChange"
          :current-page="mainPageNum"
          :page-size="mainPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="mainTotal"
          :page-count="mainTotalPages"
          :page-sizes="[5, 10, 15, 20]"
        ></el-pagination>
      </div>
    </div>

    <!-- 上传弹窗 -->
  <el-dialog
  title="碳配额项目上传"
  :visible.sync="fromVisible"
  width="70%"
  :close-on-click-modal="false"
  destroy-on-close
  @close="resetUploadForm"
>
  <el-form
    ref="uploadForm"
    :model="uploadForm"
    :rules="uploadRules"  
    size="medium"
  >
  
    <!-- 名称(一级持有机构) 对应数据库 agency_name -->
    <el-form-item 
      label="一级持有机构" 
      required
      prop="agencyName"  
    >
      <el-input
        v-model="uploadForm.agencyName"
        placeholder="请输入内容"
        style="width: 100%"
      />
    </el-form-item>

    <!-- 持仓总量(tCO2e) 对应数据库 total -->
    <el-row :gutter="20" class="form-row">
      <el-col :span="12">
        <el-form-item 
          label="持仓总量(tCO2e)" 
          required
          prop="total"  
        >
          <el-input
            v-model.number="uploadForm.total"
            placeholder="填写持仓总量"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <!-- 购入单价(¥) 对应数据库 buy_unit_price -->
      <el-col :span="12">
        <el-form-item label="购入单价(¥)" prop="buyUnitPrice">
          <el-input
            v-model.number="uploadForm.buyUnitPrice"
        
            placeholder="填写购入单价"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 购入总价(¥) 对应数据库 buy_total_price -->
    <el-row :gutter="20" class="form-row">
      <el-col :span="12">
        <el-form-item label="购入总价(¥)" prop="buyTotalPrice">
          <el-input
            v-model.number="uploadForm.buyTotalPrice"
            placeholder="自动计算或填写"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <!-- 购入日期 对应数据库 buy_date -->
      <el-col :span="12">
        <el-form-item label="购入日期" prop="buyDate">
          <el-date-picker
            v-model="uploadForm.buyDate"
            type="date"
            placeholder="选择购入日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-row>

    

    <!-- 交易所 -->
    <el-row :gutter="20" class="form-row">
      <el-col :span="12">
        <el-form-item label="交易所" prop="exchangeCode">
          <el-select
            v-model="uploadForm.carbonExchangeCode"
            placeholder="请选择交易所"
            style="width: 100%"
          >
             <el-option
            v-for="item in deliveryExchange"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <!-- 可用数量(tCO2e) 对应数据库 available_amount -->
      <el-col :span="12">
        <el-form-item 
          label="可用数量(tCO2e)" 
          required
          prop="availableAmount"  
        >
          <el-input
            v-model.number="uploadForm.availableAmount"
            placeholder="填写可用数量"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 锁定数量(tCO2e) 对应数据库 locked_amount -->
    <el-row :gutter="20" class="form-row">
      <el-col :span="12">
        <el-form-item 
          label="锁定数量(tCO2e)" 
          required
          prop="lockedAmount"  
        >
          <el-input
            v-model.number="uploadForm.lockedAmount"
            placeholder="填写锁定数量"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <!-- 冻结数量(tCO2e) 对应数据库 frozen_amount -->
      <el-col :span="12">
        <el-form-item 
          label="冻结数量(tCO2e)" 
          required
          prop="frozenAmount"  
        >
          <el-input
            v-model.number="uploadForm.frozenAmount"
            placeholder="填写冻结数量"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-row>

    <!--  对应数据库 valuation -->
    <el-row :gutter="20" class="form-row">
     
      <!-- 有效期 对应数据库 expiry_date -->
      <el-col :span="12">
        <el-form-item label="有效期" prop="expiryDate">
          <el-date-picker
            v-model="uploadForm.expiryDate"
            type="date"
            placeholder="选择有效期"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="资产状态" prop="assetsStatus">
          <el-select
            v-model="uploadForm.assetsStatus"
            placeholder="请选择"
            style="width: 100%"
          >
             <el-option
            v-for="item in assetsStatus"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>

    <!-- 签发日期 对应数据库 issuing_date -->
    <el-row :gutter="20" class="form-row">
      <el-col :span="12">
        <el-form-item 
          label="签发日期" 
          required
          prop="issuingDate"  
        >
          <el-date-picker
            v-model="uploadForm.issuingDate"
            type="date"
            placeholder="选择签发日期"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
      <!-- 签发机构 对应数据库 issuing_agency -->
      <el-col :span="12">
        <el-form-item 
          label="签发机构" 
          required
          prop="issuingAgency" 
        >
          <el-select
            v-model="uploadForm.issuingAgency"
            placeholder="请选择签发机构"
            style="width: 100%"
          >
            <el-option
            v-for="item in issuingAgency"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
    </el-row>
<!-- 持仓凭证 对应数据库 issuing_certificates -->
    <el-row :gutter="20" class="form-row">
            <el-col :span="12">
              <el-form-item label="持仓凭证" prop="issuingCertificates">
                <el-upload
                  class="upload-demo"
                  ref="uploadHold"
                  :on-change="handleTranChange"
                  :on-remove="removeFileList"
                  accept=".pdf,.docx,.xlsx,.xls,.jpg,.png"
                  style="width: 180px"
                  :action="upLoadParam.url"
                  :file-list="tranFileList"
                  :auto-upload="true"
                  :headers="{ token: upLoadParam.token }"
                  :on-success="upLoadParamTranFile"
                  :on-preview="tranFilehandlePreview"
                >
                  <el-button size="small" type="primary">选择文件</el-button>
                </el-upload>
                <div v-if="uploadForm.issuingCertificatesFileName" class="file-name">
                  已选择：{{ uploadForm.issuingCertificatesFileName }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="交易凭证" prop="tradeProof">
                <el-upload
                  class="upload-demo"
                  :on-change="handleTradeChange"
                  :on-remove="removeTradeFileList"
                  :on-success="upLoadParamTradeFile"
                  :on-preview="tradeFilehandlePreview"
                  accept=".pdf,.docx,.xlsx,.xls,.jpg,.png"
                  style="width: 180px"
                  :action="upLoadParam.url"
                  :file-list="tradeFileList"
                  :auto-upload="true"
                  :headers="{ token: upLoadParam.token }"
                >
                  <el-button size="small" type="primary">选择文件</el-button>
                  <div slot="tip" class="el-upload__tip">
                    
                  </div>
                </el-upload>
                <div v-if="uploadForm.buyCertificateFileName" class="file-name">
                  已选择：{{ uploadForm.buyCertificateFileName }}
                </div>
              </el-form-item>
            </el-col>
          </el-row>

  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="fromVisible = false">取消</el-button>
    <el-button type="primary" @click="handleSubmit">提交</el-button>
  </div>
</el-dialog>


    
    <!-- 场外上架弹窗 -->
<el-dialog
  title="场外上架"
  :visible.sync="offlineDialogVisible"
  width="50%"
  :close-on-click-modal="false"
  @close="resetOfflineForm"
  destroy-on-close
>
  <el-form
    ref="offlineForm"
    :model="offlineForm"
    :rules="offlineFormRules"
    label-width="160px"
  >
    <el-form-item label="出售数量(tCO2e)" prop="tradeQuantity">
      <el-input
        v-model.number="offlineForm.tradeQuantity"
        placeholder="请输入出售数量"
      ></el-input>
    </el-form-item>
    <el-form-item label="出售单价(¥)" prop="assetUnitPrice">
      <el-input
        v-model.number="offlineForm.assetUnitPrice"
        placeholder="请输入出售单价"
      ></el-input>
    </el-form-item>
    <el-form-item label="出售截止时间" prop="expirationDate">
      <el-date-picker
        v-model="offlineForm.expirationDate"
        type="date"
        placeholder="选择截止时间"
        clearable
      ></el-date-picker>
    </el-form-item>
    <el-form-item label="期望交割时间" prop="deliveryTime">
      <el-date-picker
        v-model="offlineForm.deliveryTime"
        type="date"
        placeholder="选择交割时间"
        clearable
      ></el-date-picker>
    </el-form-item>
    <!-- 期望交割方式 -->
<el-form-item label="期望交割方式" prop="deliveryMethod">
  <el-select
    v-model="offlineForm.deliveryMethod"
    placeholder="请选择"
    v-loading="optionsLoading"
  >
    <el-option
      v-for="item in deliveryMethod"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

<!-- 期望交割场所 -->
<el-form-item label="期望交割场所" prop="deliveryExchange">
  <el-select
    v-model="offlineForm.deliveryExchange"
    placeholder="请选择"
    v-loading="optionsLoading"
  >
   <el-option
      v-for="item in deliveryExchange"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>
  </el-form>
  <template #footer>
    <span class="dialog-footer">
      <el-button  @click="resetOfflineForm">取消</el-button>
      <el-button type="primary" @click="handleOfflineSubmit">确定</el-button>
    </span>
  </template>
</el-dialog>
      <!-- 我要买 -->
<el-dialog title="采购单" :visible.sync="dialogVisible" width="600px">
    <el-form :model="form2" label-width="160px"   class="top-aligned-form" >
      <el-form-item label="采购机构*">
        <el-input v-model="form2.institutionName" placeholder="请输入采购机构"></el-input>
      </el-form-item>
      <el-form-item label="采购联系人*">
        <el-input v-model="form2.contactsName" placeholder="请输入采购联系人"></el-input>
      </el-form-item>
      <el-form-item label="联系电话*">
        <el-input v-model="form2.contactsPhone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form2.contactsEmail" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="项目领域">
        <el-select v-model="form2.projectScopeCode" placeholder="请选择">
         <el-option
            v-for="item in projectScope"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资产类型">
        <el-select v-model="form2.assetType" placeholder="请选择">
         <el-option
            v-for="item in assetType"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型">
        <el-select v-model="form2.projectType" placeholder="请选择">
          <el-option
            v-for="item in projectType"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购数量(CO2e)*">
        <el-input v-model="form2.tradeQuantity" placeholder="请输入采购数量"></el-input>
      </el-form-item>
      <el-form-item label="询价(¥)">
        <el-input v-model="form2.assetUnitPrice" placeholder="请输入询价"></el-input>
      </el-form-item>
      <el-form-item label="截止采购日期">
        <el-date-picker
          v-model="form2.expirationDate"
          type="date"
          placeholder="请选择截止采购日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="期望交割日期">
        <el-date-picker
          v-model="form2.deliveryTime"
          type="date"
          placeholder="请选择期望交割日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="期望交割方式">
  <el-select v-model="form2.deliveryMethod" placeholder="请选择">
   <el-option
      v-for="item in deliveryMethod"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

<el-form-item label="期望交割场所">
  <el-select v-model="form2.deliveryExchange" placeholder="请选择">
   <el-option
      v-for="item in deliveryExchange"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handlecaiSubmit">提交</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
import {
  getFeiShuUpLoadProjectParams,
  getUpLoadFileParams,
} from "@/api/tenant";

export default {
  name: "CarbonQuotaAsset",
  data() {
    return {
      // 分页相关变量
      mainPageNum: 1,       // 当前页码
      mainPageSize: 10,     // 每页条数
      mainTotal: 0,         // 总记录数

      // 上传表单数据
      uploadForm: {
        id: '',
        agencyName: '',             // 名称(一级持有机构)
        total: null,                // 持仓总量(tCO2e)
        buyUnitPrice: null,         // 购入单价(¥)
        buyTotalPrice: null,        // 购入总价(¥)
        buyDate: '',                // 购入日期
        carbonExchangeCode: '',     // 交易所
        availableAmount: null,      // 可用数量(tCO2e)
        lockedAmount: null,         // 锁定数量(tCO2e)
        frozenAmount: null,         // 冻结数量(tCO2e)
        holdProofName: '',
        tradeProofName:'',
        assetsStatus: '',           // 资产状态
        expiryDate: '',             // 有效期
        issuingDate: '',            // 签发日期
        issuingAgency: '',          // 签发机构
        issuingCertificates: '',    // 签发凭证
        issuingCertificatesFileName: '', // 持仓凭证文件名
        buyCertificate:'',
        buyCertificateFileName:'',
      },

      form: {
        assetsStatus: '',         // 资产状态
        agencyName: '',           // 项目名称（搜索用）
        expiryDateStart: '',      // 开始日期
        expiryDateEnd: ''         // 结束日期
      }, 

      // 场外上架弹窗控制
      offlineDialogVisible: false,
      dialogTitle: "碳信用项目上传",
      // 我要买弹窗
      dialogVisible: false,
      
      // 场外上架表单数据
      offlineForm: {
        contactsName:'',
        contactsPhone:'',
        contactsEmail:'',
        projectId: '',
        tradeQuantity: '', // 出售数量
        assetUnitPrice: '', // 出售单价
        expirationDate: null, // 出售截止时间
        deliveryTime: null, // 期望交割时间
        deliveryMethod: '', 
        deliveryExchange: '' ,
        projectScope:'',
        projectScopeCode:'',
        projectType:'',
        institutionName:''
      },
      
      // 场外上架表单校验规则
      offlineFormRules: {
        tradeQuantity: [
          { required: true, message: '请输入出售数量', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入合法数值（最多两位小数）', trigger: 'blur' }
        ],
        assetUnitPrice: [
          { required: false, message: '请输入出售单价', trigger: 'blur' },
          { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入合法数值（最多两位小数）', trigger: 'blur' }
        ],
        expirationDate: [
          { required: false, message: '请选择出售截止时间', trigger: 'change' }
        ],
        deliveryTime: [
          { required: false, message: '请选择期望交割时间', trigger: 'change' }
        ]
      },

      optionsLoading: false,
      deliveryModeLoading: false ,
      
      // 文件上传相关
      tranFileList: [], // 持仓凭证文件列表
      tradeFileList: [], // 交易凭证文件列表
      tranFileUrl: "", // 持仓凭证飞书地址
      tradeFileUrl: "",

      // 弹窗控制
      fromVisible: false,
      projectSelectorVisible: false,
      upLoadParams: {}, // 图片上传参数
      upLoadParam: {}, // 文件上传参数
      
      // 项目选择相关
      projectSearchKey: "",
      projectList: [],
      projectTotal: 0,
      projectPageNum: 1,
      projectPageSize: 5,
      projectLoading: false,

      // 主表格相关
      tableData: [],
      tableLoading: false,
      selectedProjects: [],
      projectFilter: "",

      // 我要买的form上传到后端用
      form2: {
        publisherId: '',
        institutionName: '',
        contactsName: '',
        contactsPhone: '',
        contactsEmail: '',
        projectScopeCode: '',
        assetType: '',
        projectType: '',
        tradeQuantity: '',
        assetUnitPrice: '',
        expirationDate: '',
        deliveryTime: '',
        deliveryMethod: '',
        deliveryExchange: '',
      },

      // 碳配额项目上传表单验证规则
      uploadRules: {
        agencyName: [
          { required: true, message: "请输入一级持有机构名称", trigger: "blur" },
          { max: 100, message: "机构名称不能超过100个字符", trigger: "blur" }
        ],
        total: [
          { required: true, message: "请填写持仓总量", trigger: "blur" },
          { type: "number", message: "请输入有效的数字", trigger: "blur" }
        ],
        buyUnitPrice: [
          { type: "number", message: "请输入有效的单价", trigger: "blur" }
        ],
        carbonExchangeCode: [
          { required: true, message: "请选择交易所", trigger: "change" }
        ],
        availableAmount: [
          { required: true, message: "请填写可用数量", trigger: "blur" },
          { type: "number", message: "请输入有效的数字", trigger: "blur" }
        ],
        lockedAmount: [
          { required: true, message: "请填写锁定数量", trigger: "blur" },
          { type: "number", message: "请输入有效的数字", trigger: "blur" }
        ],
        frozenAmount: [
          { required: true, message: "请填写冻结数量", trigger: "blur" },
          { type: "number", message: "请输入有效的数字", trigger: "blur" }
        ],
        expiryDate: [
          { required: true, message: "请选择有效期", trigger: "change" }
        ],
        issuingDate: [
          { required: true, message: "请选择签发日期", trigger: "change" }
        ],
        issuingAgency: [
          { required: true, message: "请选择签发机构", trigger: "change" }
        ],
        issuingCertificates: [
          { required: true, message: "持仓凭证必须上传", trigger: "change" }
        ]
      },

      // 用户信息
      user : JSON.parse(localStorage.getItem('user') || '{}'),
      
      // 顶部统计数据
      holdTotal: '',
      available: '',
      locked: '',
      frozen: '',
      
      // 下拉列表数据
      projectScope:[],
      assetType:[],
      projectType:[],
      deliveryMethod: [],
      deliveryExchange: [],
      issuingAgency:[],
      certificationCriteria:[],
      transactionStatus:[],
      assetsStatus:[]
    };
  },

  computed: {
    // 过滤后的项目列表
    filteredProjects() {
      return this.projectList.filter((project) =>
        project.name.toLowerCase().includes(this.projectFilter.toLowerCase())
      );
    },
    // 总页数计算
    mainTotalPages() {
      if (this.mainTotal <= 0) return 0;
      return Math.ceil(this.mainTotal / this.mainPageSize);
    }
  },

  watch: {
    fromVisible(newVal) {
      if (!newVal) {
        this.resetUploadForm();
      }
    },
    // 监听购入单价变化，计算总价
    "uploadForm.buyUnitPrice"(val) {
      if (this.uploadForm.total && val) {
        this.uploadForm.buyTotalPrice = (this.uploadForm.total * val).toFixed(2);
      }
    },
    // 监听持仓总量变化，计算总价
    "uploadForm.total"(val) {
      if (this.uploadForm.buyUnitPrice && val) {
        this.uploadForm.buyTotalPrice = (val * this.uploadForm.buyUnitPrice).toFixed(2);
      }
    }
  },

  mounted() {
    this.form2.publisherId = this.user.tenantId || ''; 
    this.queryCreditSum();
    this.queryCredits();
    this.loadSelectorData();
    this.upLoadParams = getUpLoadFileParams();
    this.upLoadParam = getFeiShuUpLoadProjectParams();
  },

  methods: {
    resetOfflineForm() {
      this.offlineDialogVisible = false;
      this.offlineForm = {
        carbonProjectId: '',
        tradeQuantity: '',
        assetUnitPrice: '',
        expirationDate: null,
        deliveryTime: null,
        deliveryMethod: '',
        deliveryExchange: '',
        projectScopeCode:'',
        projectScope:'',
        projectType:'',
        institutionName:''
      };
    },

    // 提交场外上架表单
    handleOfflineSubmit() {
      this.$refs.offlineForm.validate((valid) => {
        if (valid) {
          const requestData = { ...this.offlineForm };
          this.$request.post('/trade/carbonTradeQuote/addQuota', requestData).then(res => {
            if (res.code === 200) {
              this.$message.success('场外上架提交成功');
              this.offlineDialogVisible = false;
              this.queryCredits();
              this.queryCreditSum();
            } else {
              this.$message.error(res.msg || '提交失败');
            }
          }).catch(error => {
            console.error('提交失败:', error);
          });
        }
      });
    },

    // 提交我要买
    handlecaiSubmit() {
      if(this.form2.assetType === '0140000000'){
        this.form2.assetType = '';
      }
      if(this.form2.projectType === '0040000000'){
        this.form2.projectType = '';
      }
      if(this.form2.projectScopeCode === '0030000000'){
        this.form2.projectScopeCode = '';
      }
      this.$request.post('/trade/carbonTradeQuote/addBuy', this.form2).then(res => {
        if (res.code === 200) {
          this.$message.success('采购清单提交成功');
          this.dialogVisible = false;
        } else {
          this.$message.error(res.msg || '提交失败');
        }
      });
    },

    resetUploadForm() {
      this.fromVisible = false;
      this.uploadForm = {
        id: '',
        agencyName: '',
        total: null,
        buyUnitPrice: null,
        buyTotalPrice: null,
        buyDate: '',
        carbonExchangeCode: '',
        availableAmount: null,
        lockedAmount: null,
        frozenAmount: null,
        holdProofName: '',
        tradeProofName:'',
        assetsStatus: '',
        expiryDate: '',
        issuingDate: '',
        issuingAgency: '',
        issuingCertificates: '',
        issuingCertificatesFileName: '',
        buyCertificate:'',
        buyCertificateFileName:'',
      };
      this.tranFileList = [];
      this.tradeFileList = [];
      this.tranFileUrl = "";
      if (this.$refs.uploadForm) {
        this.$refs.uploadForm.resetFields();
      }
    },

    async fetchDeliveryOptions(type) {
      this.optionsLoading = true;
      try {
        const res = await this.$request.get(`/trade/carbonTradeQuote/getDeliveryMethod/${type}`);
        if (res.code == 200) {
          return res.data;
        } else {
          this.$message.warning("获取数据失败");
          return [];
        }
      } catch (error) {
        console.error(`获取${type}失败：`, error);
        return [];
      } finally {
        this.optionsLoading = false;
      }
    },

    loadSelectorData() {
      this.$request.get('/assets/carbonCreditAssets/querySelector').then(res => {
        if(res.code === 200) {  
          this.certificationCriteria = res.data.certificationList;
          this.transactionStatus = res.data.transactionStatusList;
          this.assetsStatus = res.data.assetsStatusList;
          this.projectScope = res.data.projectScopeList;
          this.assetType = res.data.assetTypeList;
          this.projectType = res.data.projectTypeList;
          this.deliveryMethod = res.data.deliveryMethodList;
          this.deliveryExchange = res.data.deliveryExchangeList;
          this.issuingAgency = res.data.issuingAgencyList;
        }
      });
    },

    queryCredits() {
      this.tableLoading = true;
      const params = {
        ...this.form,
        tenantId: this.user.tenantId,
        pageNum: this.mainPageNum,
        pageSize: this.mainPageSize
      };

      if (params.assetsStatus === '0130000000') {
        params.assetsStatus = null;
      }

      this.$request.get('/assets/carbonQuotaAssets/queryBySelector', {
        params: params
      }).then(res => {
        this.tableLoading = false;
        if (res.code === 200) {
          this.tableData = res.data.records || [];
          this.mainTotal = res.data.total || 0;
        }
      }).catch(error => {
        this.tableLoading = false;
        console.error("查询失败:", error);
      });
    },

    handleView(id) {
        this.$router.push({
    path: '/assets/quota/quotaDetail?id=',
    query: { id: id } // 通过query传递参数，与详情页的this.$route.query.id对应
  })
    
    },

    handleSubmit() {
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          this.uploadForm.issuingCertificatesFileName = this.uploadForm.holdProofName;
          this.uploadForm.buyCertificateFileName = this.uploadForm.tradeProofName;

          this.$request({
            url: this.uploadForm.id ? '/assets/carbonQuotaAssets/update' : '/assets/carbonQuotaAssets/upload',
            method: this.uploadForm.id ? 'PUT' : 'POST',
            data: this.uploadForm
          }).then(res => {
            if (res.code === 200) {
              this.$message.success(res.msg);
              this.queryCredits();
              this.queryCreditSum();
              this.fromVisible = false;
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },

    tranFilehandlePreview(file) {
      let tranFileUrl = file.response.msg;
      window.open(tranFileUrl, '_blank');
    },

    handleTranChange(file, fileList) {
      this.tranFileList = fileList.slice(-1);
      this.uploadForm.holdProofName = file.name;
    },

    removeFileList(file, fileList) {
      this.tranFileList = [];
      this.tranFileUrl = "";
    },

    upLoadParamTranFile(response, file, fileList) {
      if (response) {
        this.tranFileUrl = response.msg;
        this.uploadForm.issuingCertificates = this.tranFileUrl;
      }
    },

    handleTradeChange(file, fileList) {
      this.tradeFileList = fileList.slice(-1);
      this.uploadForm.tradeProofName = file.name;
    },

    removeTradeFileList(file, fileList) {
      this.tradeFileList = [];
      this.uploadForm.tradeProofName = "";
      this.tradeFileUrl = "";
    },

    upLoadParamTradeFile(response, file, fileList) {
      if (response) {
        this.tradeFileUrl = response.msg;
        this.uploadForm.buyCertificate = this.tradeFileUrl;
      }
    },

    tradeFilehandlePreview(file) {
      let tradeFileUrl = file.response.msg;
      window.open(tradeFileUrl, '_blank');
    },

    handleHoldProofRemove() {
      this.uploadForm.holdProof = null;
      this.uploadForm.holdProofName = "";
      if (this.$refs.uploadForm) {
        this.$refs.uploadForm.validateField("holdProof");
      }
    },

    handleProjectPageSizeChange(newSize) {
      this.projectPageSize = newSize;
      this.projectPageNum = 1;
      this.fetchProjectList();
    },

    selectProject(row) {
      this.uploadForm.projectId = row.id;
      this.uploadForm.projectName = row.projectName;
      this.uploadForm.carbonMethodologyName = row.methodologyName || "";
      this.uploadForm.projectScopeType = row.projectScopeType || "";
      this.uploadForm.issuingDate = row.issuingDate ? new Date(row.issuingDate) : null;
      this.uploadForm.certifiedAgency = row.projectVerifier || "";
      this.uploadForm.methodologyCode = row.methodologyCode || "";
      this.projectSelectorVisible = false;
    },

    openProjectSelector() {
      this.projectSelectorVisible = true;
      this.projectPageNum = 1;
      this.fetchProjectList();
    },

    async fetchProjectList() {
      this.projectLoading = true;
      const params = {
        page: this.projectPageNum,
        pageSize: this.projectPageSize,
        projectName: this.projectSearchKey,
        tenantId: this.user.tenantId,
      };
      try {
        const res = await this.$request.get("/assets/carbonCreditAssets/list", {
          params,
        });
        if (res.code === 200) {
          this.projectTotal = Number(res.data.total) || 0;
          this.projectPageNum = Number(res.data.current) || 1;
          this.projectList = res.data.records || [];
        }
      } catch (error) {
        this.$message.error("获取项目列表失败，请稍后重试");
        console.error(error);
      } finally {
        this.projectLoading = false;
      }
    },

    queryCreditSum() {
      this.$request
        .get("/assets/carbonQuotaAssets/queryQuotaAssetsSum", {
          params: {
            tenantId: this.user.tenantId,
          },
        })
        .then((res) => {
          if (res.code === 200) {
            this.holdTotal = res.data.total || 0;
            this.locked = res.data.lockedAmount || 0;
            this.frozen = res.data.frozenAmount || 0;
            this.available = res.data.availableAmount || 0;
          }
        });
    },

    handleSelectionChange(selection) {
      console.log("选中的行：", selection);
    },

    handleOffline(row) {
      this.offlineForm.projectId = row.id;
      this.offlineDialogVisible = true;
      this.offlineForm.publisherId = this.user.tenantId;
      this.offlineForm.contactsName = this.user.accountName;
      this.offlineForm.contactsPhone = this.user.phone;
      this.offlineForm.institutionName = this.user.tenantName;
    },

    handleInner(row) {
      console.log("场内交易操作，行数据：", row);
    },

    handleProjectSearch() {
      this.resetMainPagination();
    },

    // 分页相关方法
    handleMainPageChange(val) {
      this.mainPageNum = val;
      this.queryCredits();
    },

    handleMainPageSizeChange(val) {
      this.mainPageSize = val;
      this.mainPageNum = 1;
      this.queryCredits();
    },

    resetMainPagination() {
      this.mainPageNum = 1;
      this.queryCredits();
    },

    handleProjectSelect(selection) {
      this.selectedProjects = selection;
    },

    handleProjectSelectorClose() {
      this.selectedProjects = [];
      this.projectSearchKey = "";
    },

    handleProjectPageChange(newPage) {
      this.projectPageNum = newPage;
      this.fetchProjectList();
    },

    handleHoldProofChange(file) {
      this.uploadForm.holdProof = file.raw;
      this.uploadForm.holdProofName = file.name;
    },

    handleTradeProofChange(file) {
      this.uploadForm.tradeProof = file.raw;
      this.uploadForm.tradeProofName = file.name;
    }
  }
};
</script>

<style lang="scss" scoped>
.carbon-credit-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}

::v-deep .project-selector-table {
  border: none !important;
}

::v-deep .project-selector-table .el-table__header,
::v-deep .project-selector-table .el-table__body,
::v-deep .project-selector-table .el-table__row,
::v-deep .project-selector-table th,
::v-deep .project-selector-table td {
  border: none !important;
  border-collapse: collapse !important;
}

/* 顶部栏样式 */
.top-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #e6f7ed;
  padding: 10px 20px;
  border-radius: 4px;
  margin-bottom: 20px;

  .header-left {
    display: flex;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #52c41a;
      margin-left: 8px;
    }
  }

  .header-middle {
    color: #666;
    text-align: left;
    flex: 1;
    margin: 0 20px;
    font-size: 14px;

    .stat-item {
      margin-right: 10px;
    }

    .stat-value {
      color: #6cba12;
      font-weight: 700;
    }
  }

  .header-right {
    button {
      margin-left: 10px;
      &.el-button--primary {
        border-color: #409eff;
        color: #409eff;
      }
      &.el-button--success {
        border-color: #67c23a;
        color: #67c23a;
      }
    }
  }
}

/* 筛选区域样式 */
.filter-section {
  background: #f8f9fa;
  padding: 20px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;

  .filter-row,
  .search-row {
    display: flex;
    flex-wrap: wrap;
  }

  .filter-item {
    margin-bottom: 10px;
  }

  .filter-label {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
    min-width: 60px; 
  }

  .filter-label2 {
    display: inline-block;
    font-size: 14px;
    color: #666;
    margin-bottom: 4px;
    width: 100px; 
  }

  .filter-select,
  .filter-date {
    width: 100%;
    --el-input-border-color: #dcdfe6;
  }

  .search-container {
    display: flex;
    align-items: center;
    width: 100%;
  }

  .search-input {
    flex: 1;
    margin-right: 10px;
    --el-input-border-color: #dcdfe6;
  }
}

/* 操作按钮样式 */
.operation-btns {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: center;

  .btn-text {
    cursor: pointer;
    color: #409eff;
    &.view {
      color: #409eff;
    }
    &.offline {
      color: #409eff;
    }
    &.inner {
      color: #67c23a;
    }
    &.modify {
      color: #f5a623;
    }
    &.delete {
      color: #f56c6c;
    }
    &:hover {
      text-decoration: underline;
    }
  }
}

/* 分页样式 */
.pagination {
  margin-top: 15px;
  text-align: right;
  padding: 10px 0;
}

/* 上传弹窗样式 */
.upload-dialog-content {
  padding: 20px 40px;
}

.form-row {
  margin-bottom: 5px;
}

.file-name {
  margin-top: 6px;
  color: #666;
  font-size: 12px;
  max-width: 300px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-form-item__label {
  font-weight: 1000;
}

::v-deep .el-upload__tip {
  margin-top: 5px !important;
}

/* 项目选择弹窗样式 */
.project-search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.project-pagination {
  text-align: right;
  margin-top: 15px;
}
</style>
